//将parent环境set到自己的环境中
window.electron = window.top.electron
window.$ = (args) => window.top.$(args, document);
document.notification = window.top.document.notification
document.print = window.top.document.print
document.println = window.top.document.println
document.printclear = window.top.document.printclear
window.GetDocuemtnChildNodes = window.top.GetDocuemtnChildNodes
window.GetUUID = window.top.GetUUID
document.Page = window.top.document.Page

//可以直接使用了
document.println("我是技能树可视化编辑")

const { sqlite, database } = electron.JDBC();
const Path = electron.path();
const root = electron.cwd();
const { Pvf } = electron.PvfConnect();

/**  ============拖拽功能 start============*/

/*拖拽元素响应事件 */
const handleDragStart = (e) => {
    // console.log("开始拖拽了", e)

    let dragElement = e.target
    let dragClass = dragElement.className

    switch (dragClass) {
        case "skill-col":
            // console.log("拖拽一个技能面板中的技能图标")
            e.dataTransfer.setData("from", "skillpanel")
            currentDragElement = dragElement
            break;

        case "useable-skill-img":
            // console.log("拖拽一个可用技能中的技能图标")
            e.dataTransfer.setData("from", "useable")
            currentDragElement = dragElement
            break;
    }
}


/*放置元素响应事件 */
const handleDrop = (e) => {
    //拖拽结束并且放入时触发
    // console.log("放置元素响应-放入了元素", e)
    e.preventDefault();

    let targetElement = e.target
    let targetClass = targetElement.className

    let dragFrom = e.dataTransfer.getData("from");
    let dragElement = currentDragElement


    if (targetClass == "containers clearfix" || targetClass == "useable-skill-img") {
        return handles[dragFrom]["useable"](dragElement, targetElement);
    }

    if (targetClass == "skill-col") {
        return handles[dragFrom]["skillpanel"](dragElement, targetElement);
    }
}

const handleDragOver = (e) => {
    e.preventDefault();
}

//拖拽完成时 处理
let currentDragElement;

const handles = {
    "useable": {
        "useable": (fromElement, toElement) => {
            // console.log("从[可用技能]拖动到[可用技能]",fromElement, toElement)
        },

        "skillpanel": (fromElement, toElement) => {
            // console.log("从[可用技能]拖动到[技能面板]",fromElement, toElement)
        }
    },

    "skillpanel": {
        "useable": (fromElement, toElement) => {
            // console.log("从[技能面板]拖动到[可用技能]",fromElement, toElement)
        },

        "skillpanel": (fromElement, toElement) => {
            // console.log("从[技能面板]拖动到[技能面板]",fromElement, toElement)
        }
    }
}

//右侧容器 可用技能，接收拖拽时
const rightContainerDragOver = (e) => {
    var ev = e || window.event;
    ev.preventDefault();

    //取出dataTransfer中的数据
}

/**  ============拖拽功能  end============ */

//当前使用的下拉配置  
//对应 skilltree_pvf中的version字段
let currentVersion = "默认";

//当前正在修改的内容
const currentFileContent = {
    file: null, //从pvf读取的原始文件
    newFile: null,//准备上传的文件
    keyFile: null,//修改的内容 [character job]到[/character job]之间的内容

    path: null, //pvf文件路径
    key: null,  //文件需要修改的块索引
}

//生成下拉按钮内容
const selectInit = () => {
    //检查默认使用version
    const checkVersion = () => {
        sqlite.config.queryByName("skilltree").then(rs => {
            if (!rs || rs.length <= 0) {
                sqlite.config.insert("skilltree", "默认");
            } else {
                currentVersion = rs.value;
            }
            checkSkilltreePvf();
        })
    }

    //检查数据库表是否存在
    const checkSkilltreePvf = () => {
        sqlite.tableExist("skilltree_pvf").then(exist => {
            console.log(`tableExist("skilltree_pvf")`, exist)
            if (!exist) {
                const sqlpath = Path.join(root, "tools/技能树可视化编辑/static/default.sql");
                sqlite.doFile(sqlpath).then(() => {
                    initSelectOption();
                })
            } else {
                initSelectOption();
            }
        })
    }

    //加载select配置
    const initSelectOption = () => {
        const sql = `select * from skilltree_pvf where version ='${currentVersion}' order by solt asc`;
        sqlite.all(sql).then(datas => {
            console.log("加载select数据", datas);
            if (!datas || datas.length <= 0) {
                console.log(`未能加载路径索引,请点击“修改路径索引”查看配置是否正确,当前加载索引方案为“${currentVersion}”`)
                return;
            }

            insertSelectOptin(datas)

        }).catch(err => {
            console.error(err);
            document.println("页面初始化失败," + err.toString());
        })
    }

    //写入select中
    const insertSelectOptin = (datas) => {
        const select = $("#job");
        datas.forEach(data => {
            let option = $(`<option value='${JSON.stringify({ ...data })}'>${data.name}</option>`)
            select.append(option);
        });
    }

    checkVersion();
}

//生成技能面板 横纵单元格
const skillPanelInit = () => {
    const skillPanel = $(".context-left .skill-panel")

    for (let row = 0; row < 24; row++) {

        const divRow = $(`<div class="skill-row" lv="${row * 5}" ypos="${row * 67}"></div>`)
        skillPanel.append(divRow);

        const divLv = $(`<div class="skill-lv  dnf-font">${row == 0 ? 1 : row * 5}</div>`)
        divRow.append(divLv);

        for (let col = 0; col < 11; col++) {
            const divCol = $(`<div class="skill-col" offset="${col}" xpos="${col * 47}"
                                used="false"
                                skill-index="0"
                                draggable="false"
                                ondragstart="handleDragStart(event)"
                                ondrop="handleDrop(event)" 
                                ondragover="handleDragOver(event)"
                            ></div>
            `)
            divRow.append(divCol);
        }
    }
}

//生成可用技能cell
const skillUseableInit = (datas) => {
    if (datas) {
        let ctr = $(".context-right .containers");
        ctr.html("");

        datas.forEach(skill => {
            let div = $(`<div class="skillcell" >
                            <img class="useable-skill-img" src="${skill.base64}" skill-index="${skill.index}"
                                draggable="true"
                                ondragstart="handleDragStart(event)"
                            >
                            </img>
                            <label>${skill.name}</label>
                        </div>
                `)
            ctr.append(div);
        });
    }
}

const changeJob = (value) => {
    const json = JSON.parse(value);
    console.log("changeJob", json);

    const input = $("#file-path")
    input.val(json.path);

    //清理技能面板
    $(".skill-row .skill-col").each((i, d) => {
        d.innerHTML = "";
        d.draggable = false;
    })

    //清理未分配面板


    //重新加载文件和技能
    document.println("重新加载文件和技能，请稍等...");

    //重置current
    currentFileContent.file = null;
    currentFileContent.newFile = null;
    currentFileContent.keyFile = null;
    currentFileContent.path = json.path
    currentFileContent.key = json.key;

    Pvf.getFiles([json.path]).then(rs => {
        if (!rs || rs == "") {
            document.println("从pvf连接获取文件失败")
            return;
        }

        const data = JSON.parse(rs[0]);
        // console.log(data);

        if (data.IsError) {
            document.println("从pvf连接获取文件失败 " + data.Msg || "");
            return;
        }

        let file = data.Data.replaceAll("\\r\\n", "\r\n").replaceAll("\\t", "\t")
        loadFile(file, json.key);
    })
}

const loadFile = (file, key) => {
    console.log("loadfile", key, /**file */);

    currentFileContent.file = file;
    currentFileContent.newFile = file;



    //截取出需要的职业
    {
        const cjs = file.split("[character job]");
        // console.log(cjs);

        cjs.forEach(cj => {
            cj = "[character job]" + cj;

            if (cj.indexOf(key) != -1) {
                currentFileContent.keyFile = cj
            }
        })
        // console.log(currentFileContent.keyFile)
    }

    //整理配置项
    {
        //index技能编号 icon_pos技能位置 next_skill后置技能
        currentFileContent.skillInfos = currentFileContent.keyFile
            .replaceAll("[character job]", "")
            .replaceAll("[/character job]", "")
            .split("[skill info]")

            .filter(e => e.indexOf("[index]") != -1)
            .map(e => e.replaceAll("[/skill info]", ""))
            .map(e => e.replaceAll("\r\n", ""))

            .map(e => {
                const indexOffset = e.indexOf("[index]"); //+7
                const posOffset = e.indexOf("[icon pos]"); //+10
                const nextOffset = e.indexOf("[next skill]"); //+12

                let index = null, pos = [], next = [];

                //解析index
                if (posOffset == -1) {
                    document.println("文件配置有误,请检查是否正确。未找到[icon pos]")
                    throw new Error("文件配置有误,请检查是否正确。未找到[icon pos]")

                } else {
                    index = e.substring(indexOffset + 7, e.indexOf("[icon pos]")).replaceAll("\t", "").trim()
                    index = parseInt(index);
                }

                //解析icon_pos
                if (nextOffset == -1) {
                    let posText = e.substring(posOffset + 10)
                    pos = posText.split("\t").filter(a => a != "")
                } else {
                    let posText = e.substring(posOffset + 10, nextOffset)
                    pos = posText.split("\t").filter(a => a != "").map(a => parseInt(a))
                }

                //解析next_index
                if (nextOffset != -1) {
                    let allNextText = e.substring(nextOffset)
                    let nextText = allNextText.replaceAll("\t", "").split("[next skill]")
                    next = nextText.filter(a => a != "").map(a => parseInt(a))
                }

                return {
                    // text: e,
                    index,
                    pos,
                    next,
                }
            })
        console.log("skillInfos", currentFileContent.skillInfos)
    }

    //查询技能表


    //已经使用的技能放入技能面板
    const skillPanel = $(".context-left .skill-panel")
    currentFileContent.skillInfos.forEach(skill => {
        const tr = skillPanel.find(`.skill-row[ypos='${skill.pos[1]}']`);
        const td = tr.find(`.skill-col[xpos=${skill.pos[0]}]`);

        if (td) {
            td.html(skill.index)
            td.attr("draggable", "true")
        } else {
            console.log("未在指定面板位置:", skill);
        }
    })


    //未使用的技能放入可用技能
}

const checkPvfAndNpk = () => {
    //检测pvf连接配置

    //检测npk缓存
}

//保存上传
const saveInit = () => {
    document.querySelector("#save-btn").addEventListener("click", function () {
        let motrix = [];

        //遍历技能面板
        let rows = GetDocuemtnChildNodes(document.querySelector(".context-left .skill-panel"))
        rows.forEach(row => {
            let ypos = row.getAttribute("ypos");
            let cols = GetDocuemtnChildNodes(row);
            cols.filter(e => e.getAttribute("used") == "true").forEach(col => {
                let xpos = col.getAttribute("xpos");
                let index = col.getAttribute("skill-index");

                motrix.push({
                    index,
                    xpos,
                    ypos
                })
            })
        })

        console.log(motrix)
    });
}

window.onload = function () {
    //全局字体颜色
    const topBody = window.top.document.querySelector("body")
    const body = document.querySelector("body")

    if (topBody.style.color) {
        body.style.color = topBody.style.color
    }

    document.println("请在“设置->外部连接”中填写pvf工具和npk路径，并为npk建立缓存")
    document.println("exe中默认只预留到85级，超过85会导致技能坐标跑出技能面板")

    checkPvfAndNpk();
    selectInit();
    skillPanelInit();
    saveInit();

    //@test 生成测试数据
    let datas = [
        {
            name: "上挑",
            src: "",
            index: 0,
        },
        {
            name: "三段斩",
            src: "",
            index: 1,
        },
        {
            name: "银光落刃",
            src: "",
            index: 2,
        },
    ]

    skillUseableInit(datas);
}